﻿if (typeof jQuery === 'undefined') {
    throw new Error('jquery.grid JavaScript requires jQuery');
}

if (typeof Plugin === 'undefined') {
    throw new Error('jquery.grid JavaScript requires Plugin');
}


(function ($) {
    'use strict';

    var Grid = function (el, options) {
        this.$el = $(el);
        this.namespace = _config_.grid.namespace;
        this.defaults = _config_.grid.defaults;
        this.methods = _config_.grid.methods;
        this.events = _config_.grid.events;

        this.initials = $.com.getDataFromElement(this.$el);
        this.initials = $.extend(true, {}, _config_.grid.initials, this.initials);
        this.initials.multiple = this.initials.selectable && this.initials.selectable.toString().startsWith('multiple');
        this.initColumns();
        this.originals = $.extend(true, {}, this.defaults, this.initials);
        this.originals.side = this.originals.side.toLowerCase();

        this.options = $.extend(true, {}, this.originals, options);
        this.options.serial = $.com.getSerial(16);

        //拖动参数
        this.options.sourceIndex = 0;
        this.options.targetIndex = 0;
        this.options.grid = null;
        this.options.range = { x: 0, y: 0 };//鼠标元素偏移量
        this.options.lastPos = { x: 0, y: 0, x1: 0, y1: 0 }; //拖拽对象的四个坐标
        this.options.tarPos = { x: 0, y: 0, x1: 0, y1: 0 }; //目标元素对象的坐标初始化
        this.options.theDiv = null; this.options.move = false;//拖拽对象 拖拽状态
        this.options.theDivId = 0; this.options.heDivHeight = 0; this.options.theDivHalf = 0; this.options.tarFirstY = 0; //拖拽对象的索引、高度、的初始化。
        this.options.tarDiv = null; this.options.tarFirst; this.options.tempDiv;  //要插入的目标元素的对象, 临时的虚线对象

        //grid 关联 form 或者父级 form 组件
        this.$form = $.com.hasValue(this.originals.form) ? $(this.originals.form) : this.$el.closest(_config_.selector.form);

        //grid 父级弹出框
        this.$popup = this.$el.closest(_config_.selector.popupWindow);

        //grid 关联组件
        if ($.com.hasValue(this.originals.related)) {
            this.$related = $(this.originals.related);
        }

        //处理id
        this.getNamedPrefix('type');
        this.init();
    };

    Grid.prototype = new Plugin();

    Grid.prototype.init = function () {
        this.execute(this.options.loading);

        //绑定记录查询的记录方法
        this.initBind();

        //bind change events
        this.initials.change = event => this.onChange(event);

        //设置最后一次查询的记录
        //this.initRemember();
        //初始化 grid
        this.$el.kendoGrid(this.initRemember());
        this.role = this.$el.data(this.options.role);
        if ($.com.hasValue(this.role)) {
            //if ($.com.hasValue(this.options.pageable) && this.options.pageable) {
            //    this.resize();
            //}

            this.role.dataSource._role = this;
            this.role.dataSource.options.autoQuery = true;
            localStorageSet(this);
            //if (!$.com.hasValue(this.role.initials)) {
            //    this.role.initials = this.initials.dataSource;
            //} else if (!this.options.remember) {
            //    this.initials.dataSource = $.extend(true, {}, this.role.options.dataSource);
            //    this.role.initials = this.initials.dataSource;
            //}

            this.initEvent();
        }

        this.$el.attr(_config_.attribute.initial, true);
        this.execute(this.options.loaded);
    };

    Grid.prototype.resize = function () {
        var height = this.options.tableHeight;
        if (height === 'auto') {
            var $tr = this.$el.find('table tbody tr:first');
            if (!$tr.hasValue()) {
                $tr = this.$el.find('table thead tr:first');
            }

            if ($tr.hasValue()) {
                var rowHeight = $tr.height();
                if (rowHeight > 0) {
                    var rowCount = this.role.dataSource.data().length;
                    var minRowCount = this.options.minRowCount || 10
                    var maxRowCount = this.options.maxRowCount || 10;
                    rowCount = rowCount <= minRowCount ? minRowCount : rowCount;
                    rowCount = rowCount >= maxRowCount ? maxRowCount : rowCount;
                    height = rowHeight * rowCount;
                }
            }
        }

        //TODO gird 组件没有数据时, 会显示一个横向滚动条
        //this.$el.find('.k-grid-content').height(height).width(this.$el.width() + 1);
        this.$el.find('.k-grid-pager a.k-pager-nav').removeClass('k-pager-first').removeClass('k-pager-last');
        var $rowIndex = this.$el.find('thead tr th[data-field="_rowIndex"]');
        if ($rowIndex.hasValue()) {
            $rowIndex.children(':first').remove();
            $rowIndex.children().css('margin-right', '-0.6em');
            $rowIndex.off('click');
        }
    };

    Grid.prototype.initEvent = function () {
        if (this.options.selectable) {
            this.$el.off('click.' + this.options.namespace).on('click.' + this.options.namespace, 'tbody tr', event => this.onClick(event));

            this.$el.off('dblclick.' + this.options.namespace).on('dblclick.' + this.options.namespace, 'tbody tr', event => this.onDblclick(event));
        }
    };

    Grid.prototype.dragstart = function (event) {
        this.options.theDiv = $(event.target).parent();

        //鼠标元素相对偏移量
        this.options.range.x = event.pageX - this.options.theDiv.offset().left;
        this.options.range.y = event.pageY - this.options.theDiv.offset().top;

        this.options.theDivId = this.options.theDiv.index();
        this.options.theDivHeight = this.options.theDiv.height();
        this.options.theDivHalf = this.options.theDivHeight / 2;
        this.options.move = true;
        this.options.theDiv.attr("class", function (i, origValue) {
            return origValue + " maindash";
        });
        // 创建新元素 插入拖拽元素之前的位置
        $(event.target).parent().clone().attr("style", "opacity: 0.5;background-color: black;").insertBefore(this.options.theDiv);
        $(event.target).parent().remove();
    };

    Grid.prototype.dragend = function (event, mouseup) {
        var that = this;
        this.options.theDiv.insertBefore(this.options.tempDiv);  // 拖拽元素插入到 虚线div的位置上
        $(this.options.grid).find("tr[style^='opacity: 0.5']").remove(); // 删除新建的虚线div
        this.options.move = false;
        $("body tr:last").remove();
        this.options.grid.find("tr").each(function (index) {
            if ($.com.hasValue($(this).attr('class'))) {
                if ($(this).attr('class').indexOf("maindash") >= 0) {
                    that.options.targetIndex = index;
                }
            }
        })

        this.swapRow(event);
    };

    Grid.prototype.swapRow = function (event) {
        var oldData = this.role.dataSource.data();
        var sourceData = oldData.splice(this.options.sourceIndex - 1, 1);
        oldData.splice(this.options.targetIndex, 0, sourceData[0]);
        for (var i = 0; i < oldData.length; i++) {
            oldData[i]._rowIndex = (i + 1);
        }

        this.role.dataSource.data(oldData);
        this.bindDragAndDrop();
    };

    Grid.prototype.drag = function (event) {
        var that = this;
        if (!this.options.move) return false;
        this.options.lastPos.x = event.pageX - this.options.range.x;
        this.options.lastPos.y = event.pageY - this.options.range.y;
        this.options.lastPos.y1 = this.options.lastPos.y + this.options.theDivHeight;
        // 拖拽元素随鼠标移动
        this.options.theDiv.css({ left: this.options.lastPos.x + 'px', top: this.options.lastPos.y + 'px' });
        // 拖拽元素随鼠标移动 查找插入目标元素
        var $main = $(this.options.grid).find("tr"); // 局部变量：按照重新排列过的顺序  再次获取 各个元素的坐标，
        this.options.tempDiv = $(this.options.grid).find("tr[style^='opacity: 0.5']");

        $main.each(function () {
            that.options.tarDiv = $(this);
            that.options.tarPos.x = that.options.tarDiv.offset().left;
            that.options.tarPos.y = that.options.tarDiv.offset().top;
            that.options.tarPos.y1 = that.options.tarPos.y + that.options.tarDiv.height() / 2;

            that.options.tarFirst = $main.eq(0); // 获得第一个元素
            that.options.tarFirstY = that.options.tarFirst.offset().top + that.options.theDivHalf; // 第一个元素对象的中心纵坐标

            //拖拽对象 移动到第一个位置
            if (that.options.lastPos.y <= that.options.tarFirstY) {
                that.options.tempDiv.insertBefore(that.options.tarFirst);
            }
            //判断要插入目标元素的 坐标后， 直接插入
            if (that.options.lastPos.y >= that.options.tarPos.y - that.options.theDivHalf && that.options.lastPos.y1 >= that.options.tarPos.y1) {
                that.options.tempDiv.insertAfter(that.options.tarDiv);
            }
        });
    };

    //单击事件主要用于实现选择后关联 form 组件联动效果
    Grid.prototype.onClick = function (event) {
        var data = this.getSelect();

        // clicking 事件
        var ret = this.execute(this.options.clicking, event, data);
        if ($.com.hasValue(ret) && ret === false) {
            return;
        }

        // 将选中行数据填入关联 form
        if (!$.com.isNullOrEmpty(data) && $.com.isJqueryObject(this.$related)) {
            data = $.com.getClone(data);
            if (this.$related.is(_config_.selector.form)) {
                //关联组件是 form, 用选中行刷新 form
                this.$related.form('refresh', data);
            } else if (this.$related.is(_config_.selector.popupWindow)) {
                //关联组件是 window
                var popupWindow = this.$related.data(_config_.popupWindow.namespace);
                if ($.com.hasValue(popupWindow)) {
                    //关联组件是当前容器 window, 则执行容器 window 的 select 方法
                    popupWindow.select(data);
                }
            }
        }

        // clicked 事件
        this.execute(this.options.clicked, event);
    };

    //双击事件主要用于实现和关联组件联动效果
    //grid 的关联组件目前有两种 form 和 popup
    //form 组件的联动主要是填充数据, 和 click 事件类似
    //popup组件的联动目前是调用 popup.select 方法完成进一步动作
    Grid.prototype.onDblclick = function (event) {
        var data = this.getSelect();
        if (this.options.multiple) {
            data = data[0];
        }

        // dblclicking 事件
        var ret = this.execute(this.options.dblclicking, event, data);
        if ($.com.hasValue(ret) && ret === false) {
            return;
        }

        if (!$.com.isNullOrEmpty(data) && $.com.isJqueryObject(this.$related)) {
            data = $.com.getClone(data);
            if (this.$related.is(_config_.selector.form)) {
                //关联组件是 form, 用选中行刷新 form
                this.$related.form('refresh', data);
            } else if (this.$related.is(_config_.selector.popupWindow)) {
                //关联组件是 window
                var popupWindow = this.$related.data(_config_.popupWindow.namespace);
                if ($.com.hasValue(popupWindow)) {
                    //关联组件是当前容器 window, 则执行容器 window 的 select 方法
                    if ($.com.isJqueryObject(popupWindow.$grid) && this.$el.equal(popupWindow.$grid)) {
                        popupWindow.select(data, true);
                    } else if ($.com.isJqueryObject(popupWindow.$form) && popupWindow.$form.isForm()) {
                        this.$related.trigger('open', [{ formData: data }]);
                    }
                }
            }
        }

        // dblclicked 事件
        this.execute(this.options.dblclicked, event);
    };

    /**
     * 行选择时始终触发
     * @param {any} event
     */
    Grid.prototype.onChange = function (event) {
        // changing 事件
        var ret = this.execute(this.options.changing, event);
        if ($.com.hasValue(ret) && ret === false) {
            return;
        }

        var data = undefined;
        var rows = this.role.select();
        if (this.options.multiple) {
            data = [];
            var $rows = this.$el.find('tr td :checkbox');
            if ($.com.isJqueryObject($rows)) {
                $rows.prop('checked', false);
            }

            if ($.com.isJqueryObject(rows)) {
                rows.each((index, el) => {
                    var row = this.role.dataItem(el);
                    data.push(row);
                    $(el).find('td :checkbox').prop('checked', true);
                });
            }
        } else {
            data = this.role.dataItem(rows);
        }

        // changed 事件
        this.execute(this.options.changed, event, data);
    };

    /**
     * 获取当前表格的选中行 
     */
    Grid.prototype.getSelect = function () {
        var data = [];
        var rows = this.role.select();
        if ($.com.isJqueryObject(rows)) {
            rows.each((index, el) => data.push(this.role.dataItem(el)));
        }

        if (!this.options.multiple) {
            data = data[0];
        }

        return data;
    }

    /**
     * 选择行
     * @param {any} rows 要选择的行, 不传则视为全部
     */
    Grid.prototype.select = function (rows, key) {
        var isArray = rows instanceof Array;
        if (!isArray) {
            this.role.select(rows || this.role.items());
        } else {
            var key = key || 'id';
            var selectedRows = [];
            this.role.items().each((index, el) => {
                var row = this.role.dataItem(el)
                if (rows.exist(x => x[key] == row[key])) {
                    selectedRows.push(el);
                }
            });

            this.role.select(selectedRows);
        }
    };

    /**
     * 取消选择行
     * TBC
     * @param {any} rows 要取消的行, 不传则视为全部
     */
    Grid.prototype.deselect = function (rows) {
        var selectedRows = this.role.select();
        this.role.clearSelection();
        if (this.options.multiple && $.com.isArray(rows) && $.com.isArrayLike(selectedRows)) {
            var leaveRows = [];
            var isArray = rows instanceof Array;
            selectedRows.each((index, el) => {
                if (isArray) {
                    var row = this.role.dataItem(el);
                    if (!rows.exist(x => x.id == row.id)) {
                        leaveRows.push(el);
                    }
                } else {
                    if ($(rows).filter($(el)).length === 0) {
                        leaveRows.push(el);
                    }
                }
            });
        }
    };

    Grid.prototype.refresh = function () {
        this.role.refresh();
    };

    Grid.prototype.initColumns = function () {
        if ($.com.isArray(this.initials.columns) && !$.com.isArray(this.initials.dataSource)) {
            //处理schema
            for (var i = 0; i < this.initials.columns.length; i++) {
                var column = this.initials.columns[i];
                if ($.com.hasValue(column.field)) {
                    var field = $.extend({}, column);
                    field.format = field.format || _config_.format.grid[field.type];
                    column.format = field.format;
                    var template = field.template;
                    if ($.com.isFunction(template)) {
                        delete field['template'];
                    }

                    column.data = column.data || column.dataFrom;
                    if ($.com.hasValue(column.data)) {
                        var formatter = column.formatter || '$.com.commonFormatter';
                        //column.template = item => formatter(column.data, item[column.field], item);
                        //column.template = $.com.eval(`item=>${formatter}(${column.dataFrom}, item['${column.field}'], item)`);
                        column.template = $.com.eval(`item=>${formatter}($.com.eval(${column.data}), item['${column.field}'], item)`);
                    } else if ($.com.hasValue(column.formatter)) {
                        column.template = $.com.eval(`item=>${column.formatter}('${column.field}', item['${column.field}'], item)`);
                    }

                    if (field.type === 'date' || field.type === 'time' || field.type === 'datetime') {
                        column.template = $.com.eval(`item=>$.com.dateTimeFormatter(item['${column.field}'], '${_config_.format.monemt[field.type]}')`);
                        field.type = 'date';
                    } else if (field.type === 'image') {
                        column.contentPopup = false;
                        //column.template = item => $.com.imageThumbnailFormatter(item[imageField], imageTitle, imageSize);
                        column.template = $.com.eval(`item=>$.com.imageThumbnailFormatter(item['${column.field}'], '${column.title}', ${column.size})`);
                    }

                    if (field.type === 'popup' || field.type === 'image' || field.type === 'checkbox' || field.type === 'radio') {
                        column.contentPopup = false;
                    }

                    if (column.contentPopup !== false) {
                        column.attributes = { 'class': 'popup' };
                    }

                    this.initials.dataSource.schema.model.fields[column.field] = field;
                }
            }

            //记录导航列
            this.initials.dataSource.schema.navigationColumns = this.initials.columns.filter(function (x) {
                return x.field && x.field.indexOf('.') > 0;
            });

            // 增加序号列
            if (this.initials.rowIndex) {
                this.initials.columns.unshift(_config_.grid.rowIndex);
            }

            // 多选模式增加选择列
            if (this.initials.multiple) {
                this.initials.columns.unshift(_config_.grid.rowSelect);
            }
        }
    };

    /**
     * -------------------------------------------------------
     * 记录列表查询条件代码
     * START
     */

    //记录查询条件
    Grid.prototype.initBind = function () {
        var that = this;

        this.initials.dataBinding = function (e) {
            that.execute(that.options.binding, e);

            if ($.com.hasValue(e) && $.com.hasValue(e.items) && e.items.length > 0) {
                var pageIndex = (e.sender.dataSource.page() || 1);
                var pageSize = e.sender.dataSource.pageSize() || 0;
                for (var i = 0; i < e.items.length; i++) {
                    e.items[i]._rowIndex = ((pageIndex - 1) * pageSize) + i + 1;
                }
            }
        };

        this.initials.dataBound = function (e) {
            //TODO:若是有自定义的DataBound事件先执行其自定义函数
            that.execute(that.options.bound, e);

            //判断是否有绑定form，若有绑定form默认会记录查询
            if (that.options.form && that.options.remember) {
                var uniqueHash = getDataHashString(that);

                //第一次初始化的initial的赋值
                var firstInitials = null;
                var localStorageDataString = window.localStorage.getItem(uniqueHash);

                if ($.com.hasValue(localStorageDataString)) {
                    var localStorageData = JSON.parse(localStorageDataString);
                    var localStorageFirstInitial = localStorageData.firstInitials;
                    firstInitials = $.com.hasValue(localStorageFirstInitial) ? localStorageFirstInitial : null;
                }

                if (!$.com.hasValue(firstInitials)) {
                    firstInitials = $.extend(true, {}, that.role.options);
                }

                var formData = $(that.options.form).data(_config_.form.namespace).getFormData();
                var dataSource = $.com.getDataSource(that.role);
                dataSource.filter = that.role.dataSource.filter();
                var state = {
                    columns: that.role.columns,
                    dataSource: dataSource
                };

                var dataRemember = {
                    formData: formData,
                    state: state,
                    firstInitials: firstInitials
                };

                var dataString = JSON.stringify(dataRemember);
                window.localStorage.setItem(uniqueHash, dataString);
            }

            if ($.com.hasValue(that.role) && !$.com.hasValue(that.role.tbody.data('kendoTooltip'))) {
                that.role.tbody.kendoTooltip({
                    filter: "td.popup:not(:empty)",
                    width: 200,
                    position: "bottom",
                    content: function (event) {
                        var $target = event.target;
                        if ($.com.isJqueryObject($target)) {
                            return $target.text();
                        }
                    }
                });
            }

            if (that.options.draggable) {
                that.bindDragAndDrop();
            }

            //that.resize();
            that.rowColorful();

            let $popups = that.$el.find(`tr td ${_config_.selector.popup}`);
            if ($.com.isJqueryObject($popups)) {
                $popups.popup();
            }
        };
    };

    Grid.prototype.bindDragAndDrop = function () {
        var that = this;
        that.options.grid = that.role.tbody;
        that.role.tbody.find('tr').kendoDraggable({
            cursorOffset: { top: 10 },
            dragstart: function (e) {
                that.dragstart(e);
            },
            drag: function (e) {
                that.drag(e);
            },
            hint: function (event) {
                that.options.sourceIndex = Number($(event).find("td:first").text());
                var floatContent = event.clone().addClass("hint");
                $(floatContent).css({
                    width: $(event).width(),
                    height: $(event).height(),
                    backgroundColor: '#1d7dca',
                    opacity: 0.9,
                    color: '#fff'
                });
                $(floatContent).find('td').each(function (index, td) {
                    var _td = $(event).find('td').eq(index);
                    $(td).css({
                        width: _td.width(),
                        height: _td.height(),
                        padding: _td.css('padding')
                    });
                });
                return floatContent;
            },
            dragend: function (e) {
                that.dragend(e);
            }
        });
    };

    //设置查询条件
    Grid.prototype.initRemember = function () {
        var uniqueHash = getDataHashString(this);
        var dataString = window.localStorage.getItem(uniqueHash);

        if ($.com.hasValue(dataString)) {
            var rememberData = JSON.parse(dataString);

            if ($.com.hasValue(rememberData)) {
                if (!$.com.isNullOrEmpty(rememberData.formData)) {
                    var form = $(this.options.form).data(_config_.form.namespace);
                    if ($.com.hasValue(form)) {
                        form.refresh(rememberData.formData);
                        var $advancedSearch = form.$buttons.filter('[data-button="advancedSearch"]').first();
                        if ($.com.isJqueryObject($advancedSearch)) {
                            $.com.advancedSearchColorful($advancedSearch);
                        }
                    }
                }

                return $.com.hasValue(rememberData.state)
                    ? $.extend(true, {}, this.initials, rememberData.state)
                    : this.initials;
            }
        }

        return this.initials;
    };

    /**
     * grid 执行查询的方法
     */
    Grid.prototype.query = function () {
        //查询前, 现在前置事件只需返回 false 就可以阻止事件继续执行
        var ret = this.execute(this.options.querying, event);
        if ($.com.hasValue(ret) && ret === false) {
            return;
        }

        let form = undefined;
        if ($.com.isJqueryObject(this.$form)) {
            form = this.$form.data(_config_.form.namespace);
        }

        if ($.com.hasValue(form) && this.$form.isForm()) {
            if (form.options.filterable) {
                //否则使用 grid 的 filter 区域构造查询条件, 使用 grid 数据源执行查询
                form.getQueryExpression();
                if ($.com.hasValue(this.options.side) && $.com.hasValue(this.options.url)) {
                    //否则认为 grid 需要使用数据源从服务器读取数据进行初始化
                    let url = $.com.getQueryString(form.options.dataSource.queryString);
                    if ($.com.hasValue(url)) {
                        url = this.options.url + url;
                        $.api.get(url, data => {
                            this.role.setDataSource(data);
                            this.role.dataSource.query();
                            let $parentForm = this.$el.closest(_config_.selector.form);
                            if ($.com.isJqueryObject($parentForm) && $.com.hasValue(this.options.field)) {
                                let formData = $parentForm.data(_config_.form.namespace).options.data;
                                if ($.com.hasValue(formData)) {
                                    formData[this.options.field] = data;
                                }
                            }
                        });
                    }
                } else {
                    let dataSource = $.com.getDataSource(this.role);
                    dataSource = $.com.getQueryOptions(dataSource, form.options.dataSource);
                    if ($.com.hasValue(dataSource)) {
                        if (!this.options.dataSource.type.startsWith("odata")) {
                            dataSource.page = 1;
                            dataSource.autoQuery = true;
                            if (dataSource.sort && dataSource.sort.length == 1) {
                                var orderBy = dataSource.sort[0];
                                dataSource[_config_.default.dataSource.orderby] = orderBy.field + ' ' + orderBy.dir;
                            }
                        }

                        this.role.dataSource.query(dataSource);
                        this.initEvent();
                    }

                    //var dataSource = $.com.getDataSource(this.role);
                    //dataSource = $.com.getQueryOptions(dataSource, form.options.dataSource);
                    //if ($.com.hasValue(dataSource)) {
                    //    dataSource.page = 1;
                    //    dataSource.autoQuery = true;

                    //    //TBC ***** 使用 setOptions 给 dataSource 设置值, 就会导致 grid 记住了上次查询的条件
                    //    //grid.role.setOptions({ selectable: this.options.multiple, dataSource: dataSource });
                    //    //TBC ***** 使用 dataSource.query 会导致点击刷新和翻页时丢失过滤区的条件
                    //    //grid.role.dataSource.options.transport = dataSource.transport;
                    //    this.role.dataSource.options.autoQuery = false;
                    //    this.role.setOptions({ selectable: this.options.multiple });
                    //    this.role.dataSource.options.autoQuery = true;
                    //    this.role.dataSource.query(dataSource);

                    //    this.resize();
                    //    this.initEvent();
                    //}
                }
            } else if ($.com.hasValue(this.options.field) && $.com.hasValue(form.options.data)) {
                //grid 包含 field 字段, 即为客户端初始化数据方式, 则使用关联 form 对应 field 字段数据初始化 grid
                let data = form.options.data[this.options.field] || [];
                if ($.com.isArrayLike(data)) {
                    data = $.com.toArray(data);
                }

                //过滤无效数据
                data = $.com.cleanData(data);
                this.role.dataSource.data(data || []);
                //this.resize();
                //this.role.dataSource.query();
            }
        } else {
            //否则 grid 直接执行查询
            this.role.dataSource.query();
        }

        //查询后
        this.execute(this.options.queried, event);
    }

    /**
     * grid 行着色
     */
    Grid.prototype.rowColorful = function () {
        let $rows = this.$el.find('tr[data-uid]');
        let data = this.role.dataSource.data();
        if ($.com.isJqueryObject($rows) && data.length > 0) {
            for (var index = 0; index < data.length; index++) {
                let row = data[index];
                let dataState = (row[this.options.dataStateField] || _config_.default.dataState.available).firstLowerCase();
                let $row = $rows.filter(`[data-uid="${row.uid}"]`);
                if ($.com.isJqueryObject($row)) {
                    $row.removeClass((i, c) => c.startsWith('colorful-') ? c : '');
                    switch (dataState) {
                        case _config_.default.dataState.unavailable:
                            $row.addClass('colorful-unavailable');
                            break;
                        case _config_.default.dataState.frozen:
                            $row.addClass('colorful-frozen');
                            break;
                        case _config_.default.dataState.updated:
                            $row.addClass('colorful-updated');
                            break;
                        case _config_.default.dataState.deleted:
                            $row.addClass('colorful-deleted');
                            break;
                        case _config_.default.dataState.draft:
                            $row.addClass('colorful-draft');
                            break;
                        case _config_.default.dataState.obsoleted:
                            $row.addClass('colorful-obsoleted');
                            break;
                        case _config_.default.dataState.destroyed:
                            $row.addClass('colorful-destroyed');
                            break;
                        default:
                            $row.addClass('colorful-available');
                    }
                }
            }
        }
    };

    Grid.prototype.destroy = function () {
        if ($.com.hasValue(this.role) && $.isFunction(this.role.destroy)) {
            this.role.destroy();
        }

        this.$el.removeData(_config_.grid.namespace);
        this.$el.remove();
    };

    function getDataHashString(that) {
        var uniqueString = window.location.pathname + that.options.id;
        return '_GridCache_' + $.com.hashCode(uniqueString);
    }

    function localStorageSet(that) {
        //将第一次的kendo的Initials 的 dataSource 记录到localStorage中
        var uniqueHash = getDataHashString(that);
        var dataString = window.localStorage.getItem(uniqueHash);

        //若是没有这个localStorage
        if ($.com.hasValue(dataString)) {
            var rememberData = JSON.parse(dataString);
            //是否有kendoGrid的初始值
            if (!$.com.hasValue(rememberData.firstInitials)) {
                //重新将初始化值赋上
                that.role.initials = $.extend(true, {}, that.role.options);
                rememberData.firstInitials = that.role.initials;
                var reDataString = JSON.stringify(rememberData);
                window.localStorage.setItem(uniqueHash, reDataString);
            } else {
                that.role.initials = rememberData.firstInitials;
            }
        } else {
            that.role.initials = $.extend(true, {}, that.role.options);
        }
    }

    /**
     * 记录列表查询条件代码
     * End
     * -------------------------------------------------------
     */

    // plug-in
    $.fn.grid = function (options) {
        var args = Array.prototype.slice.call(arguments, 1);
        var value = undefined;
        this.each(function () {
            var $this = $(this);
            var data = $this.data(_config_.grid.namespace);
            // initial if nover
            if ($.com.isNullOrEmpty(data)) {
                data = new Grid(this, typeof options === 'object' && options);
                $this.data(_config_.grid.namespace, data);
            }

            if (typeof options === 'string') {
                //if options is not a method
                if ($.inArray(options, data.methods) < 0) {
                    throw 'Unknown method: ' + options;
                }

                //if options is a plugin method, to execute
                value = data[options].apply(data, args);
            }
        });

        return typeof value === 'undefined' ? this : value;
    };
})(jQuery);